package com.list88zhu.common.rxhttp.http;

import com.list88zhu.common.rxhttp.http.exception.FactoryException;
import com.list88zhu.common.rxhttp.http.subscriber.ProgressSubscriber;

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * projectName rxretrofit
 * date 2017/6/21
 * description com.example.administrator.rxjavaretrofitsample.http
 */

public class HttpClient {

    private volatile static HttpClient INSTANCE;

    private HttpClient(){}

    public static HttpClient getInstance(){
        if(INSTANCE == null){
            synchronized (HttpClient.class){
                if(INSTANCE == null){
                    INSTANCE = new HttpClient();
                }
            }
        }
        return INSTANCE;
    }

    public void doHttpDeal(BaseApi baseApi){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(baseApi.getConnectionTime(), TimeUnit.SECONDS);
        builder.addInterceptor(new BaseInterceptor());
//        builder.addNetworkInterceptor(new BaseInterceptor());

        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(baseApi.getBaseUrl())
                .build();

        ProgressSubscriber subscriber = new ProgressSubscriber(baseApi);
        Observable observable = baseApi.getObservable(retrofit)
                .retryWhen(new RetryWhenNetworkException())
                .onErrorResumeNext(funcException)
                .compose(baseApi.getRxAppCompatActivity().bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(baseApi);

        observable.subscribe(subscriber);
    }

    /**
     * 异常处理
     */
    Func1 funcException = new Func1<Throwable, Observable>() {
        @Override
        public Observable call(Throwable throwable) {
            return Observable.error(FactoryException.analysisException(throwable));
        }
    };

}
